import JSZip from 'jszip';
import FileSaver from 'file-saver';
import axios from 'axios';
import { message } from 'antd';
/**
 * 
 * @param data  数据地址
 * @param fileName 压缩包名称
 */
const compressAndDownload = (data: any[], fileName?: string, level = 9) => {
    const zip = new JSZip();
    const promises: any[] = [];  //用于存储多个promise
    data.forEach((item: any) => {
        const promise = getFile(item.url).then((res: any) => {
            const fileName = item.name
            zip.file(fileName, res.data, { binary: true });
        })
        promises.push(promise)
    })
  return  new Promise((resolve, reject) => {
        Promise.all(promises).then(() => {
            zip.generateAsync({
                type: "blob",
                compression: "DEFLATE",  // STORE：默认不压缩 DEFLATE：需要压缩
                compressionOptions: {
                    level: level               // 压缩等级1~9    1压缩速度最快，9最优压缩方式
                }
            }).then((res: any) => {
                FileSaver.saveAs(res, fileName ? fileName : "压缩包.zip") // 利用file-saver保存文件
                resolve(0)
            }).catch((error) => {
                message.error("下载异常")
                reject(1)
            })
        })
    })

}
const getFile = (url: string) => {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            responseType: "blob"
        }).then((res: any) => {
            resolve(res)
        }).catch((error: any) => {
            reject(error)
        })
    })
}


const blobDown = (BlobFile: Blob, fileName = "压缩包.zip") => {
    let link = document.createElement('a')
    link.href = window.URL.createObjectURL(BlobFile)
    link.target = '_blank'
    // let filename = response.headers['content-disposition']
    link.download = decodeURI(fileName)  // 下载的文件名称
    document.body.appendChild(link)  // 添加创建的 a 标签 dom节点
    link.click()  // 下载
    document.body.removeChild(link)  //
}


export default compressAndDownload;